import axios from "axios";
import querystring from "querystring";
import errorCode from "./errorCode";
import { Message } from "element-ui";
import { filterObject } from "@/utils/filter.js";
import router from "@/permission.js";
import { getToken, removeToken } from "@/utils/auth";
import { checkReq } from "@/requestVisit"

const service = axios.create({
  timeout: 30000,
  withCredentials: true,
  baseURL: process.env.VUE_APP_URL,
  validateStatus: function (status) {
    return status >= 200 && status <= 500; // 默认的
  },
});

// request拦截器
service.interceptors.request.use(
  async config => {
    const b = await checkReq(config.url, { time: 1000, limit: 5, wait: 3000 })
    if (b) {
      // 判断是否需要token
      const token = getToken()
      if (!config.noToken) {
        config.headers.Authorization = `bearer ${token}`
      }
      // post请求
      if (
        config.method === "post" &&
        config.headers["content-type"] === "application/x-www-form-urlencoded"
      ) {
        let d = filterObject(config.data);
        config.data = querystring.stringify(d);
      }
      // get请求
      if (config.method === "get") {
        config.params = filterObject(config.params);
      }
      return config;
    } else {
      return Promise.reject(new Error('操作不合法'));
    }
  },
  (error) => {
    return Promise.reject(new Error(error));
  }
);

// response拦截器
service.interceptors.response.use(
  res => {
    const status = Number(res.status) || 200;
    const message = res.data.msg || errorCode[status] || errorCode["default"];
    let data = new Object();
    // console.log('status',status)
    if (status === 401) {
      // 登出
      removeToken();
      router.push({
        path: "/login"
      });
      return;
    } else if (
      status === 200 && res.data.code === 0
    ) {
      data = res.data.data;
    } else {
      Message({
        message: message,
        type: "error",
      });
      return Promise.reject(new Error(message));
    }
    return data;
  },
  error => {
    return Promise.reject(error);
  }
);

export default service;
